package net.oschina.app.ui;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;

import com.yzq.testzxing.zxing.android.CaptureActivity;

import net.oschina.app.MApp;
import net.oschina.app.R;
import net.oschina.app.util.PermissionUtils;
import net.oschina.app.viewpagerfragment.ExploreFragment;
import net.oschina.app.viewpagerfragment.MeFragment;
import net.oschina.app.viewpagerfragment.NewFragment;
import net.oschina.app.viewpagerfragment.NullFragment;
import net.oschina.app.viewpagerfragment.TweetFragment;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private DrawerLayout mDLayout;
    private LinearLayout mLlContent;
    private LinearLayout mLlMenu;
    private Toolbar mTBar;
    private ActionBarDrawerToggle mToggle;
    private List<Fragment> mListF;
    private FragmentTabHost mTabHost;
    private String[] mTabName;
    private int[] mImg;
    private ImageView mCenterV;
    private Dialog mDialog;
    private LinearLayout mLlExit;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //android 7.0 权限申请
        PermissionUtils.checkPermission(this,"android.permission.CAMERA","android.permission.WRITE_EXTERNAL_STORAGE"
                ,"android.permission.READ_EXTERNAL_STORAGE");

        initeView();
        initeEvent();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    private void initeEvent() {

        initeToolbar();
        /*viewpager 的四个fragment*/
        mListF = new ArrayList<>();
        mListF.add(new NewFragment());
        mListF.add(new TweetFragment());
        mListF.add(new NullFragment());
        mListF.add(new ExploreFragment());
        mListF.add(new MeFragment());

        initeFragmentTabHost();
    }

    /*底部布局的初始化*/
    private void initeFragmentTabHost() {
    /* R.drawable.btn_quickoption_selector*/
        mTabName = new String[]{"综合", "动弹", "..", "发现", "我"};
        mImg = new int[]{R.drawable.tab_icon_new, R.drawable.tab_icon_tweet, R.drawable.tab_icon_tweet
                , R.drawable.tab_icon_explore, R.drawable.tab_icon_me};

        //初始化底部标签
        /**
         * 解决低版本中间横线的问题出现
         */
        mTabHost.setup(this, getSupportFragmentManager(), R.id.main_tabcontent);
        if (android.os.Build.VERSION.SDK_INT > 10) { //大于10版本，不显示分割线
            //标签小部件，是一个View，
            TabWidget tabWidget = mTabHost.getTabWidget();
            //不显示分割线
            tabWidget.setShowDividers(0);
        }
        // 往FragmentTabHost ：添加tab标签

        for (int i = 0; i < mTabName.length; i++) {
            View view = getIndicatorView(mTabName[i], R.layout.bottom_view_a, i);
            if (i == 2) {
                view.setVisibility(View.INVISIBLE);
            }
            mTabHost.addTab(
                    mTabHost.newTabSpec(mTabName[i]).setIndicator(view),
                    mListF.get(i).getClass(), null);
        }
        //中间按钮的点击事件
        mCenterV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Toast.makeText(getApplication(), "你点击了中间按钮", Toast.LENGTH_SHORT).show();
                mDialog = new Dialog(MainActivity.this, R.style.Theme_Light_Dialog);
                View dialogView = LayoutInflater.from(MApp.mContext).inflate(R.layout.center_dialog_view, null);
                //                mDialog.setContentView(R.layout.center_dialog_view);

                //将自定义布局加载到dialog上,注意要优先将view挂载到dialog中，之后的window操作才能有效（简单讲，才能获取点击事件）
                mDialog.setContentView(dialogView);
                //获得dialog的window窗口
                Window window = mDialog.getWindow();
                //设置dialog在屏幕底部
                window.setGravity(Gravity.BOTTOM);
                //设置dialog弹出时的动画效果，从屏幕底部向上弹出
                window.setWindowAnimations(R.style.dialogStyle);
                window.getDecorView().setPadding(0, 0, 0, 0);
                //获得window窗口的属性
                android.view.WindowManager.LayoutParams lp = window.getAttributes();
                //设置窗口宽度为充满全屏
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                //设置窗口高度为包裹内容
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                //将设置好的属性set回去
                window.setAttributes(lp);

                initeDialogEvevt(dialogView);
                mDialog.show();

            }
        });
    }

    private void initeDialogEvevt(View dialogView) {
        TextView text = (TextView) dialogView.findViewById(R.id.dialog_text);
        TextView album = (TextView) dialogView.findViewById(R.id.dialog_album);
        TextView photo = (TextView) dialogView.findViewById(R.id.dialog_photo);
        TextView voice = (TextView) dialogView.findViewById(R.id.dialog_voice);
        TextView scan = (TextView) dialogView.findViewById(R.id.dialog_scan);
        TextView note = (TextView) dialogView.findViewById(R.id.dialog_note);
        text.setOnClickListener(this);
        album.setOnClickListener(this);
        photo.setOnClickListener(this);
        voice.setOnClickListener(this);
        scan.setOnClickListener(this);
        note.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.dialog_text:
                Intent intenttext = new Intent(MainActivity.this,DilogText.class);
                startActivityForResult(intenttext, 0);
                mDialog.dismiss();
                break;
            case R.id.dialog_album:
                //调用相册
                Intent intentalbum = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intentalbum, 1);
                mDialog.dismiss();
                break;
            case R.id.dialog_photo:
                Intent intentphoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // 启动相机
                startActivityForResult(intentphoto, 2);

                mDialog.dismiss();
                break;
            case R.id.dialog_voice:
                //录音
               /* Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType(ContentType.AUDIO_AMR); //String AUDIO_AMR = "audio/amr";
                intent.setClassName("com.android.soundrecorder",
                        "com.android.soundrecorder.SoundRecorder");
                startActivityForResult(intent, 3);*/
                mDialog.dismiss();
                break;
            case R.id.dialog_scan:
                // 启动二位码扫描
                Intent intentscan = new Intent(MainActivity.this, CaptureActivity.class);
                startActivityForResult(intentscan, 2);

                mDialog.dismiss();
                break;
            case R.id.dialog_note:
                // 便签
                Intent intentnote = new Intent(MainActivity.this, NewNoteActivity.class);
                startActivity(intentnote);

                mDialog.dismiss();
                break;
        }
    }

    /*toolBar的关联*/
    private void initeToolbar() {
        //通过三步来实现toolbar与drawerlayout的联动；
        //1.
        mToggle = new ActionBarDrawerToggle(this, mDLayout, mTBar, R.string.open, R.string.close);
        //2.同步
        mToggle.syncState();
        //设置监听器
        mDLayout.addDrawerListener(mToggle);

        //添加点击事件
        mTBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_setting:
                        Toast.makeText(getApplicationContext(), "正在搜索中。。", Toast.LENGTH_SHORT).show();
                        break;
                }
                return true;
            }
        });

        //退出应用事件
        mLlExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.exit(0);
            }
        });
    }


    private void initeView() {
        mDLayout = (DrawerLayout) findViewById(R.id.main_drawer);
        mTBar = (Toolbar) findViewById(R.id.main_toolbar);
        //mLlMenu = (LinearLayout) findViewById(R.id.main_drawer_menu);
        mCenterV = (ImageView) findViewById(R.id.bottm_center_img);
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mLlExit = (LinearLayout) findViewById(R.id.ll_exit);
        setSupportActionBar(mTBar);
    }

    /*一个充气创建view的方法*/
    private View getIndicatorView(String name, int layoutId, int i) {
        View v = getLayoutInflater().inflate(layoutId, null);

        TextView tv = (TextView) v.findViewById(R.id.tv);
        ImageView img = (ImageView) v.findViewById(R.id.img);
        img.setBackgroundResource(mImg[i]);
        tv.setText(name);
        return v;
    }

    //按两次返回键退出应用
    private long mExitTime=0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            if ((System.currentTimeMillis()-mExitTime)>2000){
                Toast.makeText(this, "再按一次退出开源中国", Toast.LENGTH_SHORT).show();
                mExitTime=System.currentTimeMillis();
            }else{
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
